package com.xnyzc.lhy.common.util.jt;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xnyzc.lhy.common.util.CheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Author    Snaky丶
 * Time      2018/9/5 18:01
 * Function
 */
@Slf4j
public class HttpReqUtils {

    public static String post4Multipart(String url, Part[] parts) {
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();

        PostMethod post = new PostMethod(url);
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        if (parts != null) {
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        }
        return req(client, post);
    }

    public static String post4Multipart(String url, Part[] parts, Map<String, String> map) {
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();

        PostMethod post = new PostMethod(url);
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        if (parts != null) {
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        }
        return reqWithHeader(client, post, map);
    }

    public static String post4Json(String url, String jsonStr, Map<String, String> map) throws Exception {
        //连接池
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();

        PostMethod post = new PostMethod(url);
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        post.setRequestEntity(new StringRequestEntity(jsonStr, "application/json", "utf-8"));

        return reqWithHeader(client, post, map);
    }

    public static String post4Urlencoded(String url, NameValuePair[] param) {
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();

        PostMethod post = new PostMethod(url);
        post.getParams().setContentCharset("UTF-8");
        post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        post.addParameters(param);

        return req(client, post);
    }

    private static String req(org.apache.commons.httpclient.HttpClient client, PostMethod post) {
        String response = "";
        try {
            client.executeMethod(post); // 发送请求
            response = IOUtils.toString(post.getResponseBodyAsStream(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            post.releaseConnection();
        }
        //return  response;
        return JsonFormatUtils.formatJson(response);
    }

    private static String reqWithHeader(org.apache.commons.httpclient.HttpClient client, PostMethod post, Map<String, String> map) {
        setHeader(post, map);
        return req(client, post);
    }

    public static String get(String url, Map<String, String> map) {
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        GetMethod get = new GetMethod(url);
        try {
            setHeader(get, map);
            client.executeMethod(get);
            return JsonFormatUtils.formatJson(IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            get.releaseConnection();
        }
        return "error";
    }

    private static void setHeader(HttpMethodBase method, Map<String, String> map) {
        if (map != null) {
            for (String key : map.keySet()) {
                method.setRequestHeader(key, map.get(key));
            }
        }
    }


    public static String post(String url, Part[] parts) {
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        // 设置代理
        HostConfiguration hostConfiguration = new HostConfiguration();
        hostConfiguration.setProxy("140.143.205.58", 31280);
        client.setHostConfiguration(hostConfiguration);
        PostMethod post = new PostMethod(url);
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        if (parts != null) {
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        }
        String response = "";
        try {
            post.setRequestHeader(new Header("systemDepartmentCode", URLEncoder.encode("请求部门", "utf-8")));
            post.setRequestHeader(new Header("areaCode", URLEncoder.encode("所在行政区域", "utf-8")));
            post.setRequestHeader(new Header("sponsorCode", URLEncoder.encode("请求者身份证", "utf-8")));
            post.setRequestHeader(new Header("sponsorName", URLEncoder.encode("请求者姓名", "utf-8")));
            post.setRequestHeader(new Header("powerMatters", URLEncoder.encode("主项编码", "utf-8")));
            post.setRequestHeader(new Header("subPowerMatters", URLEncoder.encode("子项编码", "utf-8")));
            post.setRequestHeader(new Header("accessCardId", URLEncoder.encode("受件人唯一标识", "utf-8")));
            post.setRequestHeader(new Header("projectId", URLEncoder.encode("办件流水号", "utf-8")));
            post.setRequestHeader(new Header("materialName", URLEncoder.encode("材料名称", "utf-8")));
            post.setRequestHeader(new Header("accessClient", URLEncoder.encode("访问端", "utf-8")));
            post.setRequestHeader(new Header("userSystemName", URLEncoder.encode("自建系统名称", "utf-8")));
            client.executeMethod(post);
            response = IOUtils.toString(post.getResponseBodyAsStream(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            post.releaseConnection();
        }
        return response;
    }

    /**
     * 获取绿码
     *
     * @return
     */
    public static Boolean getGreenCode(String phone) {
        String result = "";
        try {
            // 手机号码查询接口
//            String url = "http://hsbhzdata.hangzhou.gov.cn:8000/ESBWeb/servlets/33.1111.zj.Y7B604xUs73c7b57.SynReq@1.0";
            // 身份证查询接口
            String url = "http://hsbhzdata.hangzhou.gov.cn:8000/ESBWeb/servlets/33.1111.zj.uU4lb0350783d2fa.SynReq@1.0";
            //获取appkey 和请求秘钥
            result = post("http://hsbhzdata.hangzhou.gov.cn:8000/ESBWeb/servlets/33.1111.zj.appkeyAndrequestToken.SynReq@1.0", null);
            JSONObject json = JSONObject.parseObject(result);
            JSONArray data = json.getJSONArray("data");
            String requestToken = data.getJSONObject(0).getString("requestSecret");
            String appKey = data.getJSONObject(0).getString("app_key");
            long requestTime = System.currentTimeMillis();
            String sign = MD5Utils.encodeByMD5(appKey + requestToken + requestTime);
            Part[] parts1 = {
//                    new StringPart("sjh", "18233110173", "Utf-8"),
                    new StringPart("sfzh", phone, "Utf-8"),
                    new StringPart("appKey", appKey),
                    new StringPart("sign", sign),
                    new StringPart("requestTime", String.valueOf(requestTime)),
                    //additional 附加参数可以不填
                    new StringPart("additional", new JSONObject().toString(), "UTF-8")
            };
            // 判断是否正常
            JSONObject greenCode = JSON.parseObject(post(url, parts1));
            System.out.println(greenCode);
            log.info("获取杭州绿码返回值:[{}],手机号:[{}]", greenCode, phone);
            if (greenCode.containsKey("datas")) {
                JSONObject datas = greenCode.getJSONObject("datas");
                if (datas.containsKey("data")) {
                    JSONArray objData = datas.getJSONArray("data");
                    if (CheckUtil.collectionIsNotEmpty(objData)) {
                        JSONObject obj = objData.getJSONObject(0);
                        if (obj.getString("mzt").equals("绿码")) {
                            return true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            // 打印错误栈 ClassName.class
            log.error("{},杭州绿码调用失败,返回结果:[{}]", e, result);
        }
        return false;
    }

//    public static void main(String[] args) {
//        Boolean greenCode = getGreenCode("330125197202281324");
//        System.out.println(greenCode);
//    }


}
